// pages/detail/detail.js
const app = getApp()
const date = new Date()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    info: {},
    show: false,
    number: 1,
    price: 0,
    showDate: false,
    date: date.toLocaleDateString(),
    cdate: date.getTime(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.getStorage({
      key:"detail" + this.data.id,
      success: res=> {
        if(!res.data) {
          wx.showToast({
            title: '页面错误请重新进入',
            icon: 'none',
            duration: 2000
          })
          return
        }
        this.setData({
          info: res.data,
          price: res.data.price * this.data.number * 100
        })
      },
      fail: res=> {
        wx.showToast({
          title: '页面错误请重新进入',
          icon: 'none',
          duration: 2000
        }) 
      }
    })
  },
  onShowdate() {
    this.setData({
      showDate: true
    })
  },
  onClose() {
    this.setData({
      showDate: false
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  close() {
    this.setData({
      show: false
    })
  },
  confirmDate(e){
    console.log(e)
    let date = new Date(e.detail)
    this.setData({
      cdate: date.getTime(),
      date: date.toLocaleDateString(),
      showDate: false
    })
    
  },
  cancelDate() {
    this.setData({
      showDate: false
    })
  },
  orderTap() {
    this.setData({
      show: true
    })
  },
  getInputVaule(e) {
    this.setData({
      number: e.detail.value,
      price: this.data.info.price * e.detail.value * 100
    })
  },
  onSubmit(e) {
    app.requestUrl('/menu/post', {id: this.data.info.id, number: this.data.number, date: this.data.date}, ret=> {
      wx.showToast({
        title: '订购成功！',
        icon: 'none',
        duration: 2000,
        success: res=> {
          setTimeout(function() {
            wx.redirectTo({
              url: '/pages/order/order?'
            })
          }, 2000)
        }
      }) 
      
    }, 'POST', false)
  },

  plus(e) {
    let number = this.data.number
    if(e.currentTarget.dataset.id == 1) {
      number = number + 1
    }else{
      number = number - 1
      if(number == 0)number = 1
    }
    let price = this.data.info.price * number * 100
    this.setData({ number, price })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})